package com.kintreda.service.platform.controller;

import com.kintreda.common.config.R;
import com.kintreda.common.config.exception.CommonBaseErrorCode;
import com.kintreda.common.config.exception.CommonBaseException;
import com.kintreda.common.mybatis.entity.SysMenu;
import com.kintreda.common.mybatis.service.ISysMenuService;
import com.kintreda.common.mybatis.vos.ManagerMenuVo;
import com.kintreda.common.oauth.annotation.SetLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/platform/menu")
@Api(tags = "权限菜单")
public class MenuController {

    @Autowired
    private ISysMenuService iSysMenuService;

    @ApiOperation(value = "菜单管理")
    @GetMapping("/list")
    public R<ManagerMenuVo> menuVoR(Integer parentId, String group){
        List<ManagerMenuVo> treeList = iSysMenuService.getTreeList(parentId,group,new ArrayList<>());
        return R.ok(treeList);
    }

    @ApiOperation(value = "保存菜单")
    @PostMapping("/save")
    @SetLog("添加或修改权限菜单")
    public R<Boolean> save(@Valid @RequestBody SysMenu sysMenu){
        if (!sysMenu.getIsButton().equals(1)){
            sysMenu.setIsButton(0);
            sysMenu.setIsMenu(1);
        }else{
            sysMenu.setIsButton(1);
            sysMenu.setIsMenu(0);
        }
        iSysMenuService.saveOrUpdate(sysMenu);
        return R.ok();
    }

    @ApiOperation(value = "删除菜单")
    @DeleteMapping("/del/{menuId}")
    @SetLog("删除权限菜单")
    public R<Boolean> del(@PathVariable Integer menuId){
        List<SysMenu> childrenList = iSysMenuService.getChildrenList(menuId, null, null);
        if (ObjectUtils.isNotEmpty(childrenList)){
            throw new CommonBaseException(CommonBaseErrorCode.DEL_PERMISSION_FAIL.setErrMsg("存在子菜单,无法进行删除操作!"));
        }
        iSysMenuService.removeById(menuId);
        return R.ok();
    }
}
